package com.siyuanren.gcocp.interceptor;

import com.siyuanren.gcocp.common.exception.BaseException;
import com.siyuanren.gcocp.facade.JedisFacade;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by   guwr
 * Project_name gcocp-parent
 * Path         com.siyuanren.gcocp.interceptor.LoginInterceptor
 * Date         2017/5/31
 * Time         9:28
 * Description  登录认证的拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    /**
     * 不需要登录就能访问的uri
     */
    private static Set<String> needAuthUrls = new HashSet<>();
    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    static {
        needAuthUrls.add("advisory");
        needAuthUrls.add("hall");
        needAuthUrls.add("seat");
        needAuthUrls.add("user");
        needAuthUrls.add("visitor");
        needAuthUrls.add("training");
        needAuthUrls.add("order");
//        needAuthUrls.add("file");
    }

    @Autowired
    private JedisFacade jedisFacade;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        logger.info("LoginInterceptor.preHandle");
        //获取请求的URL
        String uri = request.getRequestURI();

        String[] split = StringUtils.split(uri, '/');

        if (split == null || split.length == 0) {
            return true;
        }
        String allow = split[0];
        if (!needAuthUrls.contains(allow)) {
            logger.info("allow = {}", allow);
            return true;
        }
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            logger.info("未登录");
            throw BaseException.NOT_LOGIN_ERROR;
        }

        boolean exist = jedisFacade.tokenExist(token);
        if (!exist) {
            logger.info("会话超时");
            throw BaseException.NOT_LOGIN_ERROR;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
